import {getNormalType} from "./types";
/*
 * 防抖
 */
export const debounce = function(fn, delay = 500) {
  let timer = null;
  let self = this;
  let args = arguments;
  let count = 0;
  return function() {
    clearTimeout(timer);
    if (count == 0) {
      // 第一次立即执行
      fn.apply(self, args);
      count++;
    } else {
      timer = setTimeout(function() {
        fn.apply(self, args);
        count++;
      }, wait);
    }
  };
};

/*
 * 节流
 */
export const throttle = (fn, delay = 100) => {
  let timer = null;

  return function() {
    if (timer) {
      return;
    }
    timer = setTimeout(() => {
      fn.apply(this, arguments);

      timer = null;
    }, delay);
  };
};
/*
 * 深拷贝
 */
export const deepClone = (source) =>{
  try{
    let target=source.constructor === Array ? [] : {};
    let names = Object.getOwnPropertyNames(source)//获取source的所有属性，包括不可遍历的；
    for(let i =0;i<names.length;i++) {
      let desc = Object.getOwnPropertyDescriptor(source, names[i])//返回指定对象上一个自有属性对应的属性描述
      if(typeof (desc.value)==="object" && desc.value!==null) {
        let obj =deepClone(desc.value)
        Object.defineProperty(target,names[i], {
          configurable: desc.configurable, //不可删除
          enumerable: desc.enumerable,  //是否可遍历
          value: obj,
          writable: desc.writable,  //是否可写
        })   
      } else {
        Object.defineProperty(target, names[i], desc)
      }
    }
    return target
  }catch(err) {
    console.log(new Error(err))
    return source
  }
}
/*
 * 获取storage的值
 */
export function getNormalStorage({strKey, defaultValue, type}) {
  let data;
  try {
    data = JSON.parse(localStorage.getItem([strKey])) || {}
    if(type && getNormalType(data) !== type) {
      data = defaultValue;
    }
  }catch(err) {
    data = defaultValue;
  };
  return data;
}